package com.zhang.autotouch;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.projection.MediaProjectionManager;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.zhang.autotouch.bean.AppInfo;
import com.zhang.autotouch.bean.GameManage;
import com.zhang.autotouch.bean.ScreenInfo;
import com.zhang.autotouch.fw_permission.FloatWinPermissionCompat;
import com.zhang.autotouch.service.AutoTouchService;
import com.zhang.autotouch.service.FloatingService;
import com.zhang.autotouch.service.ScreenRecordService;
import com.zhang.autotouch.utils.AccessibilityUtil;
import com.zhang.autotouch.utils.ToastUtil;

import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.android.Utils;
import org.opencv.core.Mat;
import com.benjaminwan.ocrlibrary.*;

import com.zhang.autotouch.service.*;

@SuppressLint("SetTextI18n")
public class MainActivity extends AppCompatActivity implements ServiceConnection {

    private static final String TAG = "MainApp";
    private static final int REQUEST_CODE = 1000;

    private TextView tvStart;
    private final String STRING_START = "开始";
    private final String STRING_ACCESS = "无障碍服务";
    private final String STRING_ALERT = "悬浮窗权限";

    static
    {
        System.loadLibrary("native-lib");
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){
            Toast.makeText(getApplicationContext(), "横屏", Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(getApplicationContext(), "竖屏", Toast.LENGTH_SHORT).show();
        }

        getScreenBaseInfo();
    }

    /**
     * 权限申请
     */
    private void checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String[] permissions = new String[]{Manifest.permission.RECORD_AUDIO
                    , Manifest.permission.WRITE_EXTERNAL_STORAGE
                    , Manifest.permission.READ_EXTERNAL_STORAGE
                    , Manifest.permission.CAMERA
            };
            for (String permission : permissions) {
                if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this, permissions, 200);
                    return;
                }
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[]
            grantResults) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && requestCode == 200) {
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    Intent intent = new Intent();
                    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    Uri uri = Uri.fromParts("package", getPackageName(), null);
                    intent.setData(uri);
                    startActivityForResult(intent, 200);
                    return;
                }
            }
        }
    }

    /**
     * 获取屏幕录制的权限
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void startScreenRecording() {
        // TODO Auto-generated method stub
        MediaProjectionManager mediaProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
        Intent permissionIntent = mediaProjectionManager.createScreenCaptureIntent();
        startActivityForResult(permissionIntent, REQUEST_CODE);
    }

    /**
     * 导入 Open CV 库
     */
    private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
        @Override
        public void onManagerConnected(int status) {
            switch (status) {
                case LoaderCallbackInterface.SUCCESS:
                {
                    Log.i(TAG, "OpenCV loaded successfully");
                } break;
                default:
                {
                    super.onManagerConnected(status);
                } break;
            }
        }
    };

    /**
     * 获取屏幕相关数据
     */
    private void getScreenBaseInfo() {
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        ScreenInfo.getInstance().init(metrics.widthPixels, metrics.heightPixels, metrics.densityDpi);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        if(resultCode == RESULT_OK && requestCode == 200){
            checkPermission();
        }

        if(requestCode == REQUEST_CODE) {
            if(resultCode == RESULT_OK) {
                // 获得权限，启动Service开始录制
                Intent service = new Intent(this, ScreenRecordService.class);
                service.putExtra("code", resultCode);
                service.putExtra("data", data);
                service.putExtra("audio", ScreenInfo.getInstance().isAudio());
                service.putExtra("width", ScreenInfo.getInstance().getScreenWidth());
                service.putExtra("height", ScreenInfo.getInstance().getScreenHeight());
                service.putExtra("density", ScreenInfo.getInstance().getScreenDensity());
                service.putExtra("quality", ScreenInfo.getInstance().isVideoSd());
                //startService(service);
                bindService(service, this, BIND_AUTO_CREATE);
                // 已经开始屏幕录制，修改UI状态
                AppInfo.getInstance().setCapRunState(true);

                Log.i(TAG, "Started screen recording");
            } else {
                Toast.makeText(this, "User cancelled", Toast.LENGTH_LONG).show();
                Log.i(TAG, "User cancelled");
            }
        }
    }

    /**
     * 关闭屏幕录制，即停止录制Service
     */
    private void stopScreenRecording() {
        // TODO Auto-generated method stub
        Intent service = new Intent(this, ScreenRecordService.class);
        stopService(service);
    }

    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        ScreenRecordService.MyBinder myBinder = (ScreenRecordService.MyBinder)iBinder;
        ScreenRecordService screenRecordService = myBinder.getService();
        GameManage.getInstance().setScreenRecordService(screenRecordService);
        screenRecordService.setCallback(new ScreenRecordService.Callback() {
            @Override
            public void onBitmapChange(Bitmap data) {
//                ivLog.post(new Runnable() {
//                    @Override
//                    public void run() {
//                        if(isShow)
//                            ivLog.setImageBitmap(data);
//                    }
//                });
            }
        });
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {

    }

    private void loadImg(){
        Mat matHuodong = new Mat();
        Mat matTesting = new Mat();
        Mat matColseWindow = new Mat();
        Mat matHdBaotu = new Mat();

        Bitmap temp = BitmapFactory.decodeResource(getResources(), R.drawable.huodong);
        Utils.bitmapToMat(temp, matHuodong);
        GameManage.getInstance().setMatHuodong(matHuodong);
        temp.recycle();

        temp = BitmapFactory.decodeResource(getResources(), R.drawable.testing);
        Utils.bitmapToMat(temp, matTesting);
        GameManage.getInstance().setTesting(matTesting);
        temp.recycle();

        temp = BitmapFactory.decodeResource(getResources(), R.drawable.close_window);
        Utils.bitmapToMat(temp, matColseWindow);
        GameManage.getInstance().setCloseWindow(matColseWindow);
        temp.recycle();

        temp = BitmapFactory.decodeResource(getResources(), R.drawable.hd_baotu);
        Utils.bitmapToMat(temp, matHdBaotu);
        GameManage.getInstance().setHdBaotu(matHdBaotu);
        temp.recycle();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 加载OPEN CV库
        if (!OpenCVLoader.initDebug()) {
            Log.d(TAG, "Internal OpenCV library not found. Using OpenCV Manager for initialization");
            OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_0_0, this, mLoaderCallback);
        } else {
            Log.d(TAG, "OpenCV library found inside package. Using it!");
            mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
        }

        // 加载ocr引擎
        

        // 权限检测
        checkPermission();

        getScreenBaseInfo();

        startScreenRecording();

        tvStart = findViewById(R.id.tv_start);
        tvStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (tvStart.getText().toString()) {
                    case STRING_START:
                        ToastUtil.show(getString(R.string.app_name) + "已启用");
                        startService(new Intent(MainActivity.this, FloatingService.class));
                        moveTaskToBack(true);
                        break;
                    case STRING_ALERT:
                        requestPermissionAndShow();
                        break;
                    case STRING_ACCESS:
                        requestAcccessibility();
                        break;
                    default:
                        break;
                }
            }
        });
        ToastUtil.init(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        checkState();

        loadImg();
    }

    private void checkState() {
        boolean hasAccessibility = AccessibilityUtil.isSettingOpen(AutoTouchService.class, MainActivity.this);
        boolean hasWinPermission = FloatWinPermissionCompat.getInstance().check(this);
        if (hasAccessibility) {
            if (hasWinPermission) {
                tvStart.setText(STRING_START);
            } else {
                tvStart.setText(STRING_ALERT);
            }
        } else {
            tvStart.setText(STRING_ACCESS);
        }
    }

    private void requestAcccessibility() {
        new AlertDialog.Builder(this).setTitle("无障碍服务未开启")
                .setMessage("你的手机没有开启无障碍服务，" + getString(R.string.app_name) + "将无法正常使用")
                .setPositiveButton("去开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 显示授权界面
                        try {
                            AccessibilityUtil.jumpToSetting(MainActivity.this);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                })
                .setNegativeButton("取消", null).show();
    }

    /**
     * 开启悬浮窗权限
     */
    private void requestPermissionAndShow() {
        new AlertDialog.Builder(this).setTitle("悬浮窗权限未开启")
                .setMessage(getString(R.string.app_name) + "获得悬浮窗权限，才能正常使用应用")
                .setPositiveButton("去开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 显示授权界面
                        try {
                            FloatWinPermissionCompat.getInstance().apply(MainActivity.this);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                })
                .setNegativeButton("取消", null).show();
    }
}
